<?php

namespace app\wap\logic;
use think\Db;
class UsersLogic
{
    public function thirdUserPay($openid){
        $userid = 0;
        $userPayId = 0;
        $userInfo = Db::name('user')->where('openid',$openid)->find();
        if(empty($userInfo)){
            //如果该用户不存在   查询用户付款表  user_pay表
            $userPayInfo = db('user_pay')->where('openid',$openid)->find();
            if(empty($userPayInfo)){
                $data['openid'] = $openid;
                $data['points'] = 0;
                $data['create_time'] = time();
                $data['update_time'] = time();
                $userPayId = db('user_pay')->insert($data,false,true);
            }else{
                $userPayId = $userPayInfo['id'];
            }
        }else{
            $userid = $userInfo['user_id'];
        }
        return array('status'=>1,'msg'=>'登陆成功','userid'=>$userid,'userPayId'=>$userPayId);
    }
    public function payUserInfo($userPayId){
        $userInfo = Db::name('user_pay')->where('id',$userPayId)->find();
        return $userInfo;
    }
    public function thirdLogin($data){
        if(isset($data['unionid'])){
            //如果设置了unionid就通过unionid查询用户
            $where['unionid'] = $data['unionid'];
        }else{
            //通过fwh_openid查询用户
            $where['openid'] = $data['openid'];
        }
        $userInfo = Db::name('user')->where($where)->find();
        if(!$userInfo){
            //没有就创建一个用户
            $map['openid'] = $data['openid'];
            $map['wxapp_id'] = 10001;
            $map['nickName'] = $data['nickname'];
            $map['gender'] = $data['sex'];
            $map['avatarUrl'] = $data['head_pic'];
            $map['unionid'] = $data['unionid'];
            $map['province'] = $data['province'];
            $map['city'] = $data['city'];
            $map['create_time'] = time();
            $map['update_time'] = time();
//            $map['subscribe'] = $data['subscribe'];
//            $map['subscribe_time'] = $data['subscribe_time'];
            $userId = Db::name('user')->insert($map,false,true);
            $userInfo = Db::name('user')->where('user_id',$userId)->find();
        }else{
            if(!$userInfo['openid']){
                $upData['openid'] = $data['openid'];
                $upData['nickName'] = $data['nickname'];
                $upData['avatarUrl'] = $data['head_pic'];
                Db::name('user')->where('user_id',$userInfo['user_id'])->update($upData);
            }
        }
        return array('status'=>1,'msg'=>'登陆成功','result'=>$userInfo);
    }
    public function userInfo($userId){
        $userInfo = Db::name('user')->where('user_id',$userId)->find();
        return $userInfo;
    }
}